package com.cash.loan.modular.cash.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cash.loan.common.result.PageResult;
import com.cash.loan.common.upload.QiniuService;
import com.cash.loan.common.util.PageBeanUtil;
import com.cash.loan.modular.cash.dao.LoanArticleTypeMapper;
import com.cash.loan.modular.cash.dao.LoanStrategyMapper;
import com.cash.loan.modular.cash.model.LoanArticleType;
import com.cash.loan.modular.cash.model.LoanStrategy;
import com.cash.loan.modular.cash.service.StrategyService;
import com.cash.loan.modular.cash.transfer.vo.ImageItem;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Administrator
 * @Date 2018-07-20 13:44
 */
@Service
public class StrategyServiceImpl implements StrategyService {

    private static final String BIG_PIC = "bigPic";

    private static final String GROUP_PIC = "groupPic";

    private static final String SMALL_PIC = "smallPic";

    @Autowired
    private LoanStrategyMapper strategyMapper;

    @Autowired
    private LoanArticleTypeMapper articleTypeMapper;

    @Autowired
    private QiniuService qiniuService;

    @Override
    public PageResult<Map<String, Object>> getList(Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage,pageSize);
        List<Map<String,Object>> strategyList = strategyMapper.getList();

        if(strategyList == null && strategyList.size() == 0) {
            List<Map<String,Object>> list = new ArrayList<>();
            PageResult<Map<String,Object>> pageResult = new PageResult<>();
            pageResult.setDataList(list);
            return pageResult;
        }
        List<Map<String,Object>> resultList = dealStrategyList(strategyList);
        PageResult<Map<String,Object>> pageResult = PageBeanUtil.toPageResult(strategyList);
        pageResult.setDataList(resultList);
        return pageResult;
    }

    @Override
    public Map<String, Object> getDetailById(Long id) {
        Map<String,Object> result = strategyMapper.getDetailById(id);

        if(result == null) {
            return new HashMap<String,Object>(1);
        }

        if(result.get("createTime") != null) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            result.put("createTime",dateFormat.format((Date) result.get("createTime")));
        }
        if(result.get("content") != null) {
            JSONArray jsonArray = JSONArray.parseArray((String) result.get("content"));
            result.put("content",jsonArray);
        }
        if(StringUtils.isNotBlank((String) result.get("imgUrlList"))) {
            String urlListJsonStr = (String) result.get("imgUrlList");
            List<ImageItem> imageItemList = JSONArray.parseArray(urlListJsonStr,ImageItem.class);
            imageItemList.stream().forEach(imageItem -> {
                if(BIG_PIC.equals(imageItem.getType())) {
                    imageItem.setUrl(qiniuService.getUrl(imageItem.getUrl()) + "?imageView2/1/w/640/h/300");
                } else if(GROUP_PIC.equals(imageItem.getType()) || SMALL_PIC.equals(imageItem.getType())) {
                    imageItem.setUrl(qiniuService.getUrl(imageItem.getUrl()) + "?imageView2/1/w/370/h/245");
                }
            });
            result.put("urlList",imageItemList);
            result.put("url",imageItemList.get(0).getUrl());
            result.remove("imgUrlList");
        } else {
            result.put("urlList",new JSONArray());
            result.put("url","");
            result.remove("imgUrlList");
        }
        return result;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void strategyScan(Long id) {
        strategyMapper.updateViewNumById(id);
    }

    @Override
    public List<Map<String, Object>> searchStrategy(String keyword) {
        List<Map<String,Object>> strategyList = strategyMapper.getSearchList(keyword);

        if(strategyList == null && strategyList.size() == 0) {
            List<Map<String,Object>> list = new ArrayList<>();
            return list;
        }
        List<Map<String,Object>> resultList = dealStrategyList(strategyList);
        return resultList;
    }

    @Override
    public List<Map<String, Object>> getAllStrategyList() {
        List<LoanArticleType> articleTypeList = articleTypeMapper.selectList(new EntityWrapper<LoanArticleType>());
        List<Map<String,Object>> result = new ArrayList<>();
        articleTypeList.stream().forEach(loanArticleType -> {
            Map<String,Object> map = new HashMap<>();
            map.put("id",loanArticleType.getId());
            map.put("name",loanArticleType.getName());
            result.add(map);
        });
        return result;
    }

    @Override
    public List<Map<String, Object>> getStrategysByCateId(Integer id) {
        List<Map<String,Object>> strategyList = strategyMapper.getStrategysByCateId(id);
        if(strategyList == null && strategyList.size() == 0) {
            List<Map<String,Object>> list = new ArrayList<>();
            return list;
        }
        List<Map<String,Object>> resultList = dealStrategyList(strategyList);
        return resultList;
    }

    private List<Map<String,Object>> dealStrategyList(List<Map<String,Object>> strategyList) {
        List<Map<String,Object>> resultList = new ArrayList<>();
        strategyList.stream().forEach(map -> {
            if(map.get("content") != null) {
                String outline = "";
                JSONArray jsonArray = JSONArray.parseArray((String) map.get("content"));
                String parag = (String) ((JSONObject) jsonArray.get(0)).get("val");
                if(parag.length() >= 50) {
                    outline = parag.substring(0,50).replace("\n","");
                } else {
                    outline = parag.replace("\n","");
                }
                map.put("outline",outline);
                map.remove("content");
            }
            if(map.get("createTime") != null) {
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String createTime = dateFormat.format((Date) map.get("createTime"));
                map.put("createTime",createTime);
            }
            if(StringUtils.isBlank((String) map.get("imgUrlList"))) {
                map.put("urlList",new JSONArray());
                map.put("url","");
                map.remove("imgUrlList");
            } else {
                String urlListJsonStr = (String) map.get("imgUrlList");
                List<ImageItem> imageItemList = JSONArray.parseArray(urlListJsonStr,ImageItem.class);
                imageItemList.stream().forEach(imageItem ->{
                    if(BIG_PIC.equals(imageItem.getType())) {
                        imageItem.setUrl(qiniuService.getUrl(imageItem.getUrl()) + "?imageView2/1/w/640/h/300");
                    } else if(GROUP_PIC.equals(imageItem.getType()) || SMALL_PIC.equals(imageItem.getType())) {
                        imageItem.setUrl(qiniuService.getUrl(imageItem.getUrl()) + "?imageView2/1/w/370/h/245");
                    }
                });
                map.put("urlList",imageItemList);
                map.put("url",imageItemList.get(0).getUrl());
                map.remove("imgUrlList");
            }
            resultList.add(map);
        });
        return resultList;
    }
}
